﻿using CommunityToolkit.Mvvm.Input;
using Mapster;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using UpperComputer.Application;
using UpperComputer.WPF.Entry.Common;
using UpperComputer.WPF.Entry.Common.Extensions;
using UpperComputer.WPF.Entry.Models;
using UpperComputer.WPF.Entry.Views;

namespace UpperComputer.WPF.Entry.ViewModels;

public class UserOperationViewModel : OperationViewModel
{
    private BaseUserResultDto _user = new();
    public BaseUserResultDto User
    {
        get => _user;
        set => SetProperty(ref _user, value);
    }

    public ObservableCollection<BaseRoleUserDto> RoleUserDtos { get; set; } = new ObservableCollection<BaseRoleUserDto>();

    public NameValueModel<byte>[] SexList { get; set; }

    public NameValueModel<bool>[] IsActives { get; set; }

    private BaseRoleUserDto _currentRoleUser;
    public BaseRoleUserDto CurrentRoleUser
    {
        get => _currentRoleUser;
        set => SetProperty(ref _currentRoleUser, value);
    }

    public IAsyncRelayCommand<string> UserRoleOperationCommand { get; }

    private readonly IBaseUserService _userService;

    public UserOperationViewModel(IBaseUserService userService,long id)
    {
        _userService = userService;
        Id = id;
        SexList = new NameValueModel<byte>[] {
                new NameValueModel<byte>(Lang["未知"], 0),
                new NameValueModel<byte>(Lang["男"], 1),
                new NameValueModel<byte>(Lang["女"], 2),
            };

        IsActives = new NameValueModel<bool>[] {
                new NameValueModel<bool>(Lang["是"], true),
                new NameValueModel<bool>(Lang["否"], false)
            };

        CurrentRoleUser = null;

        UserRoleOperationCommand = new AsyncRelayCommand<string>(UserRoleOperationCommand_Execute);
    }

    private async Task UserRoleOperationCommand_Execute(string parameter, CancellationToken cancellationToken)
    {
        if (parameter == null)
        {
            return;
        }
        if (parameter == "Post")
        {
            UserRoleSelectControl userRoleSelectControl = Furion.App.GetService<UserRoleSelectControl>();
            object result = await userRoleSelectControl.ShowCustomDialog(Constant.DIALOG_IDENTIFIER_MENU);
            if (result is null and not BaseRoleResultDto)
            {
                return;
            }
            BaseRoleResultDto role = (BaseRoleResultDto)result;
            if (RoleUserDtos.Any(p => p.RoleCode == role.Code))
            {
                Error = "已存在当前角色，请勿重复添加";
                return;
            }
            RoleUserDtos.Add(new BaseRoleUserDto
            {
                Account = User.Account,
                RoleCode = role.Code,
                RoleName = role.DisplayName,
            });
        }
        else
        {
            MessageBoxResult mbr = this.ShowQuestionBox("确定要删除吗");
            if (mbr != MessageBoxResult.OK)
            {
                return;
            }
            _ = RoleUserDtos.Remove(CurrentRoleUser);
        }
    }

    protected override async Task LoadAsync(object parameter, CancellationToken cancellationToken)
    {
        if (!IsAdd)
        {
            User = await _userService.Get(Id, cancellationToken);
            foreach (BaseRoleUserDto item in User.BaseRoleUser)
            {
                RoleUserDtos.Add(item);
            }
        }
    }

    protected override async Task OkAsync(object parameter, CancellationToken cancellationToken)
    {
        if (!IsValidated || !User.IsValidated)
        {
            return;
        }

        if (User.Account == Constant.ADMIN && !User.IsActive)
        {
            Error = "超级管理员不能被禁用";
            return;
        }

        await TryExecuteCommandAysnc(async cancellationToken =>
        {
            User.BaseRoleUser.Clear();
            foreach (BaseRoleUserDto item in RoleUserDtos)
            {
                item.Account = User.Account;
                User.BaseRoleUser.Add(item);
            }

            if (IsAdd)
            {
                BaseUserCreateDto input = User.Adapt<BaseUserCreateDto>();
                _ = await _userService.Post(input, cancellationToken);
            }
            else
            {
                _ = await _userService.Put(User, cancellationToken);
            }
            CloseRootDialog(true);
        }, cancellationToken);
    }
}
